package com.lyy.converter;

import com.lyy.Vo.ProductCategoryTreeNodeVO;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CategoryTreeBuilder {

    /**
     * 构建多级
     * @param nodes
     * @return
     */
    public static List<ProductCategoryTreeNodeVO> build(List<ProductCategoryTreeNodeVO> nodes){
        //根节点
        List<ProductCategoryTreeNodeVO> rootMenu= new ArrayList<>();
        for (ProductCategoryTreeNodeVO nav: nodes){
            if (nav.getPid()==0){
                nav.setLev(1);
                rootMenu.add(nav);
            }
        }
        //根据ProductCategoryTreeNodeVO类的order排序
        Collections.sort(rootMenu,ProductCategoryTreeNodeVO.order());
        //为根节点设置子节点，getChild是递归用的
        for (ProductCategoryTreeNodeVO nav : rootMenu){
            //获取根节点下的所有子节点，使用getChild方法
            List<ProductCategoryTreeNodeVO> childList = getChild(nav, nodes);
            //给根节点设置子节点
            nav.setChildren(childList);
        }
        return rootMenu;
    }

    public static List<ProductCategoryTreeNodeVO> getChild(ProductCategoryTreeNodeVO pNode, List<ProductCategoryTreeNodeVO> nodes){
        //子菜单
        List<ProductCategoryTreeNodeVO> childList = new ArrayList<>();
        for (ProductCategoryTreeNodeVO nav :nodes){
            //遍历所有节点，将所有节点的的父id与传过来的根节点的id比较，相等说明为该根节点的子节点
            if (nav.getPid().equals(pNode.getId())){
                nav.setLev(pNode.getLev()+1);
                childList.add(nav);
            }
        }
        //递归
        for (ProductCategoryTreeNodeVO nav : childList){
            nav.setChildren(getChild(nav,nodes));
        }
        //排序
        Collections.sort(childList,ProductCategoryTreeNodeVO.order());
        //如果节点没有子节点，返回一个空list(递归退出)
        if (childList.size()==0){
            return null;
        }
        return childList;
    }
}
